package com.ticket.sass.provider.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.common.entity.tenant.CinemaEntity;
import com.ticket.sass.provider.dto.input.cinema.CinemaListInput;
import com.ticket.sass.provider.mapper.CinemaMapper;
import com.ticket.sass.provider.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 影院列表 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-03-06
 */
@Service
public class CinemaServiceImpl extends ServiceImpl<CinemaMapper, CinemaEntity> implements BaseService<CinemaEntity> {

        public Map<Long, List<CinemaEntity>> getCinemasByTenantIds(List<Long> tenantIds) {
            if (tenantIds.size() == 0){
                return new HashMap<>();
            }
            Map<Long, List<CinemaEntity>> cinemaCountsMap = new HashMap<>();
            
            // 使用 QueryWrapper 构建查询条件
            QueryWrapper<CinemaEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("tenant_id", tenantIds);
            
            // 查询符合条件的租户影院绑定列表
            List<CinemaEntity> tenantCinemaMaps = baseMapper.selectList(queryWrapper);
            
            // 将查询结果按租户ID分组放入 Map 中
            for (CinemaEntity tenantCinemaMap : tenantCinemaMaps) {
                Long tenantId = tenantCinemaMap.getTenantId();
                List<CinemaEntity> cinemaList = cinemaCountsMap.getOrDefault(tenantId, new ArrayList<>());
                cinemaList.add(tenantCinemaMap);
                cinemaCountsMap.put(tenantId, cinemaList);
            }
            
            return cinemaCountsMap;
        }
    
    public IPage<CinemaEntity> iPage(CinemaListInput input) {
        // 创建分页对象，传入当前页码和每页记录数
        Page<CinemaEntity> page = new Page<>(input.getPageNum(), input.getPageSize());
        
        // 构建查询条件
        QueryWrapper<CinemaEntity> queryWrapper = new QueryWrapper<>();
        if (input.getName() != null && !input.getName().isEmpty()) {
            queryWrapper.like("name", input.getName());
        }
        if (input.getTenantIds() != null && input.getTenantIds().size() > 0) {
            queryWrapper.in("tenant_id", input.getTenantIds());
        }
        queryWrapper.orderByDesc("id");
        
        // 执行分页查询
        return this.page(page, queryWrapper);
    }
}
